import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'

const uaVersions = function () {
    let u = navigator.userAgent
    // let app = navigator.appVersion
    return {
        trident: u.indexOf('Trident') > -1, //IE内核
        presto: u.indexOf('Presto') > -1, //opera内核
        webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
        gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,//火狐内核
        mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
        ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
        android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, //android终端
        iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
        iPad: u.indexOf('iPad') > -1, //是否iPad
        webApp: u.indexOf('Safari') == -1, //是否web应该程序，没有头部与底部
        weixin: u.indexOf('MicroMessenger') > -1, //是否微信 （2015-01-22新增）
        qq: u.match(/\sQQ/i) == " qq" //是否QQ
    }
}()
const origin = `${window.location.protocol}//${window.location.host}`
export default {
    origin,
    store: {
        get(name) {
            const data = localStorage.getItem(name)
            try {
                return JSON.parse(data)
            } catch (e) {
                return data
            }
        },
        set(key, value) {
            let data = value
            if (typeof value === 'object') {
                data = JSON.stringify(value)
            }
            localStorage.setItem(key, data)
        },
        remove(key) {
            localStorage.removeItem(key)
        },
        clear() {
            localStorage.clear()
        }
    },
    // 获取网址中的query参数
    getUrlParam(name) {
        let url = '?' + (window.location.href.split('?')[1] || '')
        let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)")
        // 匹配目标参数
        let result = url.substr(1).match(reg)
        //返回参数值
        return result ? decodeURIComponent(result[2]) : null
    },
    dateFormat(date = new Date(), format = 'YYYY-MM-DD') {
        return dayjs(date).format(format)
    },
    dayjs,
    /*
    * @param {Object} obj @default null - 必传项，需要格式化的对象
    * */
    queryStringify: (obj, prefix) => {
        var pairs = []
        for (var key in obj) {
            if (!obj.hasOwnProperty(key)) {
                continue
            }

            var value = obj[key]
            var enkey = encodeURIComponent(key)
            var pair
            if (typeof value === 'object') {
                pair = queryStringify(value, prefix ? prefix + '[' + enkey + ']' : enkey)
            } else {
                pair = (prefix ? prefix + '[' + enkey + ']' : enkey) + '=' + encodeURIComponent(value)
            }
            pairs.push(pair)
        }
        return pairs.join('&')
    },
    // 设备信息
    browser: {
        versions: uaVersions,
        language: (navigator.browserLanguage || navigator.language).toLowerCase(),
        isIos: uaVersions.ios,
        isWx: uaVersions.weixin,
        isAndroid: uaVersions.android,
    },
    // 设置网页标题
    setTitle(title = '$TEXT$网') {
        document.title = title
        let frame = document.createElement('iframe')
        frame.style.display = 'none'
        frame.addEventListener('load', e => {
            setTimeout(() => {
                document.body.removeChild(frame)
            }, 1000)
        })
        document.body.appendChild(frame)
    },
    toNewTagPage(url) {
        let a = document.createElement('a')
        a.href = url
        a.target = '_blank'
        document.body.append(a)
        a.click()
        document.body.removeChild(a)
    },
    validate(data, rules, cb) {
        let go = true
        let msg = ''
        for (let i in rules) {
            let val = data[i]
            for (let item of rules[i]) {
                if (item.require || item.require === undefined) {
                    if (Array.isArray(val)) {
                        if (val.length === 0) {
                            go = false
                            msg = item.message
                            cb(go, msg)
                            return
                        }
                    }
                    if (typeof (val) === 'string') {
                        if (val.trim().length === 0) {
                            go = false
                            msg = item.message
                            cb(go, msg)
                            return
                        }
                    }
                }
            }

        }
        if (cb) {
            cb(go, msg)
        }
    }
}
